<script setup lang="tsx">
import { PropType, reactive, watch } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { labelSaveApi } from '@/api/Operation'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'

const { t } = useI18n()
const { required, lengthRange } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const rules = reactive({
  name: [required(), lengthRange({ min: 1, max: 4 })]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const saveTag = async (data: any) => {
  const param = {
    id: data.id,
    name: data.name
  }
  const res = await labelSaveApi(param)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return saveTag(formData)
  }
}

// 重置Form
const reset = async () => {
  const elForm = await getElFormExpose()
  setValues({ id: '' })
  elForm?.resetFields()
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  reset,
  submit
})
</script>

<template>
  <Form :rules="rules" labelSuffix=":" @register="formRegister" :schema="formSchema" />
</template>
